import { ref, computed, Ref } from 'vue';
import isEqual from 'lodash/isEqual';
import type { Cell, Column, TableState } from '../types';

export function useHistoryManager(
  tableData: Ref<Cell[][]>,
  columns: Ref<Column[]>,
  historyRef?: Ref<TableState[]>,
  historyIndexRef?: Ref<number>
) {
  // 历史记录状态
  const history = historyRef ?? ref<TableState[]>([]);
  const historyIndex = historyIndexRef ?? ref(-1);

  // 计算属性
  const isRedoDisabled = computed(() => {
    const historyLength = history.value?.length || 0;
    return historyIndex.value >= historyLength - 1 || historyLength === 0;
  });

  const isUndoDisabled = computed(() => {
    return historyIndex.value <= 0;
  });

  // 保存状态方法
  const saveState = () => {
    const currentState = {
      tableData: tableData.value,
      columns: columns.value
    };

    // 限制历史记录数量，避免内存泄漏
    if (history.value.length > 50) {
      history.value.splice(0, 10); // 删除前10条记录
      historyIndex.value -= 10;
    }

    // 如果历史记录为空，直接保存初始状态
    if (history.value.length === 0) {
      history.value.push({
        tableData: JSON.parse(JSON.stringify(currentState.tableData)),
        columns: JSON.parse(JSON.stringify(currentState.columns))
      });
      historyIndex.value = 0;
      return;
    }

    // 获取历史记录中最新状态
    const latestState = history.value[history.value.length - 1];

    // 使用 lodash 的 isEqual 进行深度比较
    const isTableDataChanged = !isEqual(currentState.tableData, latestState.tableData);
    const isColumnsChanged = !isEqual(currentState.columns, latestState.columns);

    // 只有当数据发生变化时才保存状态
    if (isTableDataChanged || isColumnsChanged) {
      history.value.splice(historyIndex.value + 1);
      history.value.push({
        tableData: JSON.parse(JSON.stringify(currentState.tableData)),
        columns: JSON.parse(JSON.stringify(currentState.columns))
      });
      historyIndex.value++;
    }
  };

  // 撤销方法
  const undo = (clearSelection: (selectedCells: Set<string>) => void, selectedCells: Ref<Set<string>>) => {
    if (historyIndex.value > 0 && history.value.length > 0) {
      historyIndex.value--;
      const state = history.value[historyIndex.value];
      if (state) {
        try {
          tableData.value = JSON.parse(JSON.stringify(state.tableData));
          columns.value = JSON.parse(JSON.stringify(state.columns));
          clearSelection(selectedCells.value);
        } catch (error) {
          console.error('Undo operation failed:', error);
          // 恢复索引
          historyIndex.value++;
        }
      }
    }
  };

  // 重做方法
  const redo = (clearSelection: (selectedCells: Set<string>) => void, selectedCells: Ref<Set<string>>) => {
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++;
      const state = history.value[historyIndex.value];
      if (state) {
        try {
          tableData.value = JSON.parse(JSON.stringify(state.tableData));
          columns.value = JSON.parse(JSON.stringify(state.columns));
          clearSelection(selectedCells.value);
        } catch (error) {
          console.error('Redo operation failed:', error);
          // 恢复索引
          historyIndex.value--;
        }
      }
    }
  };

  return {
    // 状态
    history,
    historyIndex,

    // 计算属性
    isRedoDisabled,
    isUndoDisabled,

    // 方法
    saveState,
    undo,
    redo
  };
}
